Webpack

Include other projects modules (reduers, actions, components, etc)

When you are working with ejected create-react-app code you can setup webpack to load other node modules to use in your project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// webpack.config.prod.js and webpack.config.dev.js
const fs = require('fs')
...
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: [
paths.appSrc,
fs.realpathSync(path.resolve(paths.appNodeModules, './some-package/src')),
fs.realpathSync(path.resolve(paths.appNodeModules, './some-other-package/src'))
],
loader: require.resolve('babel-loader'),
options: {
compact: true
}
},
...

Then you can include a module from this package, for example a reducer:

1
import someReducer from '../../node_modules/some-package/src/reducers/someReducer'

Issues

  • When you try to import a component you get this error in test environment:

    1
    SyntaxError: Unexpected token import

    If you are including modules with ES6 code you have to tell jest to un-ignore this files, you can do it modifying package.json jest properties

    1
    2
    3
    4
    5
     "jest": {
    "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\](?!some-package).+\\.(js|jsx|mjs)$"
    ]
    },

Embed css styles in webpack prod files

1
2
3
4
5
// config/webpack.config.prod.js
...
test: /\.css$/,
loader: 'style-loader!css-loader'
...

How to use sass in create-react-app projects

1
2
3
4
5
6
7
8
9
10
11
12
13
// config/webpack.config.dev.js
...
{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
...
1
2
3
4
5
6
7
8
9
// config/webpack.config.prod.js

...
test: /\.s?css$/,
...
{
loader: require.resolve('sass-loader'),
},
...
1
2
3
4
5
// package.json
...
"node-sass": "^4.6.1",
"sass-loader": "^6.0.6",
...

Tools

⬆︎TOP